<?php
class Geo_State_model extends MY_Model
{
	public
		$table = 'geo_states',
		$prKey = 'id'
	;
	
	function __construct()
	{
		parent::__construct();

		$this->fields = array(
			'id' => '',
			'id_countries' 	=> T_('Country'),
			'name' 		 	=> T_('State'),
			'code' 			=> T_('Code'),
			'declension' 	=> T_('Название области в родительном падеже'),
			'capital_name' 	=> T_('Название областного центра'),
			'capital_declension' => T_('Название центра в родительном падеже')
		);

		$this->rules = array(
			'id_countries' 	=> "trim|strip_tags|required|is_natural_no_zero|max_length[10]",	
			'name' 			=> "trim|strip_tags|required|max_length[32]",	
			'code' 			=> "trim|strip_tags|max_length[4]",		
			'declension' 	=> "trim|strip_tags|max_length[32]",
			'capital_name' 	=> "trim|strip_tags|max_length[32]",
			'capital_declension' => "trim|strip_tags|max_length[32]",
		);
	}
	
	function getSelectOptions($id_countries = 840)
	{
		$options = array();
		
		if ($id_countries == 0)
		{
			return array();				
		}
		else if ($id_countries != null)
		{
			$this->db->where('id_countries', $id_countries);
		}
		
		$this->db->order_by('name');
		$list = $this->db->get($this->table)->result();
		
		if (!empty($list))
		{
			foreach ($list as $row)
			{
				$options[$row->id] = $row->name; 
			}
			
			return $options;				
		}		
	}

	function hasRegions($id_state)
	{
		$sql = 'SELECT COUNT(id) AS num FROM geo_regions WHERE id_states='. $id_state;
		$result = $this->db->query($sql)->row();
		
		return $result->num;
	}

	function getCountryByIdState($id_state)
	{
		$sql = 'SELECT c.* FROM '.$this->table.' s, geo_countries c WHERE s.id_countries=c.iso_nr AND s.id='. $id_state;
		$result = $this->db->query($sql)->row();
		
		return $result;
	}
		
	function search($config = array())
	{
		$config = array_merge(array('rowsOnPage' => 5, 'order' => 'id'), $config);
		if ($this->input->post('per_page'))
		{
			$config['rowsOnPage'] = $this->input->post('per_page');
			$per_page = 0;
		}		
		else if ($this->input->get('per_page'))
		{
			$per_page = $this->input->get('per_page');
		}
		else
		{
			$per_page = 0;
		}

		$order 		= $this->input->get_post('order');
		$direction 	= $this->input->get_post('direction');
		$search 	= $this->input->get_post('search');
		$id_countries = $this->input->get_post('id_countries');

		// main sql		
		$sql = '';
		$sql .= ' FROM '.$this->table.' s, geo_countries c';
		$sql .= ' WHERE c.iso_nr=s.id_countries ';  
			
		if ($search)
		{
			$sql .= ' AND s.name LIKE ' . $this->db->escape('%' . $search . '%'); 
		}
		
		switch ($order)
		{
			default:
				$sql .= ' ORDER BY s.id';
				$direction = 'DESC';
		}
		
		$sql .= ($direction == 'DESC') ? ' DESC' : ' ASC';

		// pagination config
		$config['base_url'] = Xurl_add(Xregenerate_url('per_page,search', true), 'search', $search);
		$config['per_page'] = $config['rowsOnPage'];
		//$config['total_rows'] = $this->getRowCount($sql);

		//$this->pagination->initialize($config); 
		
		// main sql
		$sql = 'SELECT s.*, c.name AS country_name' . $sql;// . sprintf(' LIMIT %d, %d', $per_page, $config['per_page']); 

		$this->data['list'] = $this->db->query($sql)->result();

		$this->data['per_page'] 	= $per_page;
		$this->data['search'] 		= $search;
		$this->data['id_countries'] = $id_countries;  
	}	
	
	function delete($items_serialized = null)
	{
		$items = explode("&", $items_serialized);
		
		$report = "";
		foreach ($items as $id)
		{	
			/*if ($this->geo_state_model->hasRegions($id) > 0)
			{
				$this->log->writeMessage('error', T_('Для этой области заданы районы. Удаление невозможно.'));
				$report .= ",0"; // don't deleted
			}
			else
			{*/
				//$data = $this->geo_state_model->get($id);
				
				$res = $this->db->delete($this->table, array($this->prKey => $id));
				
				if (is_null($res))
				{
					$this->log->writeMessage('error', T_('Error. State was not removed.'));
					$report .= ",0"; // don't deleted
				}
				else
				{
					$this->log->writeMessage('done', T_('State was removed.'));
					$report .= ",1"; // deleted					
				}				
			//}			
		}
		return substr($report, 1);
	}

	function insert($data)
	{
		if (!empty($data))
		{
			parent::insert($data);

			if ($this->db->insert_id() > 0)
			{
				$this->log->writeMessage('done', T_('State was added succesfully.'));
				
				return TRUE;
			}
			else
			{
				$this->log->writeMessage('error', T_('Error! State was not created.'));
				
				return FALSE;
			}
		}		
	}

	function update($data)
	{
		if (!empty($data))
		{
			$res = parent::update($data);

			$this->log->writeMessage('done', T_('Saved succesfully.'));

			return TRUE;			
		}		
	}	
}
?>